/**
 * author:Administrator
 * date:2016/3/2
 * desc:TODO
 */
"use strict";

var Router = require('koa-router');
var config = require('../../config/index.js');
var appUtil = require('../../common/appUtils.js');
let bodyParser = require('koa-better-body');
let koabody = bodyParser();

let managerCmdService = require('../../ddd/application/managerCmdService.js');
let commonQueryService = require('../../ddd/application/commonQueryService.js');
//
var __pathPrefix = '/api/v1/location';
appUtil.appLog('router:' + __pathPrefix + ',file=' + __filename);
var router = new Router({prefix: __pathPrefix});
module.exports = router.routes();

router.get('/', function*() {
  let locList = yield commonQueryService.allLocation();
  this.body = locList;
});

/**
 * create location
 * post /api/v1/location
 * {name,pid}
 */
router.post('/', koabody, function*() {
  // check if manager
  let manager = checkLogin(this);
  if (!manager) {
    this.status = 401;
    return this.body = 'not manager';
  }

  let name = this.request.body.fields.name;
  let pid = this.request.body.fields.pid;
  let loc = yield managerCmdService.createLocation(name, pid);
  this.body = loc;
});

/**
 * 检测登录状态
 */
function checkLogin(ctx) {
  let manager = ctx.session.manager;
  return manager;
}